//
//  BDRefundViewController.m
//  BeidouMall
//
//  Created by qie on 16/4/19.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDRefundViewController.h"

@interface BDRefundViewController ()
{
    UITextView *_nowEditTextView;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;


@end

@implementation BDRefundViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"申请退款";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"refundCell"];
    
    // 商品图片
    NSString *storeImageUrl = _goodList[indexPath.row][@"commodity"][@"icon"];
    UIImageView *storeImageView = (UIImageView *)[cell viewWithTag:101];
    if (![storeImageUrl isEqual:[NSNull null]]) {
        [storeImageView sd_setImageWithURL:[NSURL URLWithString:storeImageUrl] placeholderImage:[UIImage imageNamed:@"imageUser_no"]];
    }
    // 商品名称
    UITextView *goodDescTextView = (UITextView *)[cell viewWithTag:102];
    NSString *goodDesc = _goodList[indexPath.row][@"commodity"][@"name"];
    if (![goodDesc isEqual:[NSNull null]]) {
        goodDescTextView.text = goodDesc;
    }
    // 商品现价
    UILabel *priceNowLabel = (UILabel *)[cell viewWithTag:103];
    NSString *goodNowPrice = _goodList[indexPath.row][@"price"];
    if (![goodNowPrice isEqual:[NSNull null]]) {
        priceNowLabel.text = [NSString stringWithFormat:@"¥ %.2f",[goodNowPrice floatValue]];
    }
    // 商品个数
    UILabel *numLabel = (UILabel *)[cell viewWithTag:104];
    NSString *goodNum = _goodList[indexPath.row][@"num"];
    if (![goodNum isEqual:[NSNull null]]) {
        numLabel.text = [NSString stringWithFormat:@"x %ld",(long)[goodNum integerValue]];;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat textViewHeight = 48.0;
    NSString *goodDesc = _goodList[indexPath.row][@"commodity"][@"name"];
    if (![goodDesc isEqual:[NSNull null]]) {
        textViewHeight = [goodDesc boundingHeightWithSize:CGSizeMake(kScreen_Width - 104.0, CGFLOAT_MAX) font:[UIFont systemFontOfSize:12.0] lineSpace:8.0];
        textViewHeight = textViewHeight < 48 ? 48 : textViewHeight;
    }
    return textViewHeight + 287;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 10)];
    view.backgroundColor = RGBColor(238, 238, 238);
    return view;
}

#pragma mark - textView delegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    _nowEditTextView = textView;
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    //判断加上输入的字符，是否超过界限
    NSString *str = [NSString stringWithFormat:@"%@%@", textView.text, text];
    if (str.length > 256)
    {
        textView.text = [textView.text substringToIndex:256];
        [MBProgressHUD showToast:self.view withText:@"请输入1-256个字哟"];
        return NO;
    }
    
    UIView *superView = textView.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    UILabel *placeholderLabel = (UILabel *)[cell viewWithTag:106];
    
    if (![text isEqualToString:@""]) {
        placeholderLabel.hidden = YES;
    }
    
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {// 空格
        placeholderLabel.hidden = NO;
    }
    return YES;
}

#pragma mark - scrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([_nowEditTextView isFirstResponder]) {
        [_nowEditTextView resignFirstResponder];
    }
}

#pragma mark - IBActions

- (IBAction)commitButtonPressed:(UIButton *)sender {
    if (_nowEditTextView.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:@"退货原因为空"];
    } else {
        sender.enabled = NO;
        NSString *orderId = _goodList[0][@"orderId"];
        NSString *commodityId = _goodList[0][@"commodity"][@"commodityId"];
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@"申请退货中"];
        
        NSString *url = [NSString stringWithFormat:@"%@%@?orderId=%@&commodityId=%@&refundReason=%@",
                         [BDNetworking shareInstance].baseUrl,
                         Apply_Refund,
                         orderId,
                         commodityId,
                         _nowEditTextView.text];
        url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"PUT" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            sender.enabled = YES;
            if (error != nil) {
                NSLog(@"申请退货失败:%@",error);
                hud.labelText = @"申请退货失败";
                [hud hideAfterDelay:0.5];
            } else {
                hud.labelText = @"申请退货成功";
                [hud hideAfterDelay:0.5];
                NSLog(@"result = %@",results);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self.block(@"success");
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
        }];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
